import { pageCuesTopic, pageCuesTopicInit } from '@/services/api/api-cues-topic';
import { LightFilter, ProFormSelect, ProFormTreeSelect, ProList } from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Input, TreeSelect } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableTopicManageDetails from './TableTopicManageDetails';
import TableTopicManageSetting from './TableTopicManageSetting';

interface TableTopicManageProps {
  mode: number;
  loading: boolean;
  industryIds: any[];
  actionRef?: ActionType;
  onRefurbish: () => void;
}

const TableTopicManage: React.FC<TableTopicManageProps> = (props) => {
  const userRef = useRef<ActionType>();

  const access = useAccess();
  // const actionRef = useRef<ActionType>();

  useEffect(() => {
    if (props.loading) {
      userRef.current?.reload();
      props.onRefurbish();
    }
  }, [props.loading]);

  /**
   * 行业
   */
  const [queryParam, setQueryParamState] = useState({});

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          key: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined  ,        children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pageCuesTopic({ ...params, ...queryParam, mode: props.mode });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  /**
   * 查询单位
   */
  const [queryOrganizations, setQueryOrganizationsState] = useState<any>();

  /**
   * 加载 页面初始化信息
   * @param key
   */
  const loadPageCuesTopicInitData = async () => {
    try {
      const response = await pageCuesTopicInit({ mode: props.mode });
      if (response.code === 0) {
        setQueryOrganizationsState(readyTreeData(response.data.queryOrganizations));
      }
    } catch (error) {}
  };

  useEffect(() => {
    loadPageCuesTopicInitData();
  }, []);

  return (
    <>
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          gap: 8,
        }}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
          }}
        >
          <Input.Search
            placeholder="查询标题"
            enterButton="搜索"
            allowClear
            style={{ maxWidth: 522, width: '100%' }}
            onChange={(e) => {
              setQueryParamState({ ...queryParam, name: e.target.value });
            }}
            onSearch={(value) => {
              userRef.current?.reset();
            }}
          />
          <TableTopicManageSetting
            onRefurbish={() => {
              userRef.current?.reload();
            }}
          />
        </div>

        <div
          style={{
            display: 'flex',
            gap: 12,
          }}
        ></div>
      </div>
      {queryOrganizations && (
        <LightFilter
          style={{
            marginBottom: 16,
          }}
          initialValues={{}}
          onValuesChange={(value) => {
            setQueryParamState(value);
            userRef.current?.reset();
          }}
          onFinish={async (values) => console.log(values.sex)}
        >
          <ProFormSelect
            name="recordStates"
            label="状态"
            mode="multiple"
            options={[
              {
                label: '申请',
                value: 1,
              },
              {
                label: '退回',
                value: 2,
              },
              {
                label: '撤回',
                value: 5,
              },
              {
                label: '废弃',
                value: 4,
              },

              {
                label: '通过',
                value: 3,
              },
            ]}
          />
          <ProFormSelect
            name="isLinkage"
            label="联动"
            options={[
              {
                label: '是',
                value: 1,
              },
              {
                label: '否',
                value: 0,
              },
            ]}
          />
          <ProFormSelect
            name="industryIds"
            label="行业"
            mode="multiple"
            showSearch
            options={props.industryIds}
          />
          <ProFormTreeSelect
            name="createdOrganizationIds"
            label="单位"
            width="xl"
            placeholder="选择单位"
            fieldProps={{
              treeData: queryOrganizations,
              treeCheckable: true,
              showCheckedStrategy: TreeSelect.SHOW_PARENT,
            }}
          />
        </LightFilter>
      )}

      <ProList<CuesTopicData.TopicPage>
        header={false}
        headerTitle={false}
        ghost={true}
        itemCardProps={{
          ghost: false,
        }}
        pagination={{
          defaultPageSize: 12,
          showSizeChanger: false,
        }}
        actionRef={userRef}
        request={request}
        showActions="hover"
        grid={{ gutter: 18, column: 4 }}
        onItem={(record: any) => {
          return {
            onMouseEnter: () => {
            },
            onClick: () => {
            },
          };
        }}
        renderItem={(item: CuesTopicData.TopicPage, index: number) => {
          return (
            <TableTopicManageDetails
              item={item}
              onRefurbish={() => {
                userRef.current?.reload();
              }}
            />
          );
        }}
        rowKey={'id'}
        toolBarRender={false}
      />
    </>
  );
};

export default TableTopicManage;
